package com.shawn.server.service;

import com.alibaba.fastjson.JSON;
import com.shawn.autoconfig.template.EMTemplate;
import com.shawn.autoconfig.template.SmsTemplate;
import com.shawn.commons.utils.JwtUtils;
import com.shawn.commons.utils.RC;
import com.shawn.dubbo.api.CommentsApi;
import com.shawn.dubbo.api.UserApi;
import com.shawn.dubbo.api.UserInfoApi;
import com.shawn.dubbo.api.UserLikeApi;
import com.shawn.model.entity.User;
import com.shawn.model.vo.ErrorResult;
import com.shawn.server.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.util.*;

@Slf4j
@Service
public class UserService {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private EMTemplate emTemplate;

    @Autowired
    private FreezeService freezeService;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private CommentsApi commentsApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @Autowired
    private MqMessageService messageService;


    public ResponseEntity sendShortMessage(String phone) throws Exception {
        //验证当前用户是否被禁用登录
        User user = userApi.findByPhone(phone);
        if (!Objects.isNull(user)){
            freezeService.checkFreeze(user.getId(),RC.FREEZING_LOGIN);
        }

        String findCode = redisTemplate.opsForValue().get(RC.CHECK_CODE + phone);
        if (findCode != null) {
            return ResponseEntity.ok("验证码已发送!");
        }
        //生成验证码
//        String code = RandomStringUtils.randomNumeric(6);
        String code = "111111";
        //将验证码存入redis,五分钟失效!
        redisTemplate.opsForValue().set(RC.CHECK_CODE + phone, code, Duration.ofMinutes(5));

        //调用模板发送短信
//        String message = smsTemplate.sendShortMessage(phone, code);
        String message = "ok";

        log.info("短信验证码:{}已发送!", code);
        return ResponseEntity.ok(message);
    }



    public ResponseEntity loginCheck(String phone, String verificationCode) {
        //获取存入redis的验证码
        String code = redisTemplate.opsForValue().get(RC.CHECK_CODE + phone);
        if(Strings.isEmpty(code)||!code.equals(verificationCode)){
            //验证码失效,抛出登录异常
                throw new BusinessException(ErrorResult.loginError());
        }
        //验证成功,删除redis验证码
        redisTemplate.delete(RC.CHECK_CODE+phone);
        //查找该用户
        User user = userApi.findByPhone(phone);
        boolean isNew = false;
        if (user==null){
            //新用户,保存该用户
           user = new User();
            user.setMobile(phone);
            user.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));
            Long userId = userApi.save(user);
            //注册环信服务
            boolean res = emTemplate.registeredMember("hx" + userId, RC.INIT_PASSWORD);
            if (res){
                user.setHxUser("hx"+userId);
                user.setHxPassword(RC.INIT_PASSWORD);
                //更新用户信息
                userApi.update(user);
                log.info("环信服务已注册!");
            }
            user.setId(userId);
            isNew = true;
        }
        //记录用户行为
        messageService.sendLogMessage(user.getId(),isNew?"0102":"0101","user",null);
        //老用户直接登录
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",user.getId());
        map.put("phone",user.getMobile());

        String token = JwtUtils.getToken(map);
        //将用户数据存入redis中 鉴别多点登录,以及密码修改后刷新token
        String jsonString = JSON.toJSONString(user);
        redisTemplate.opsForValue().set(RC.TOKEN+token,jsonString,Duration.ofHours(1));

       /* log.warn("开始加载,用户点赞喜欢信息...");
        //查询评论表,将当前用户的点赞信息,一次性加载进入redis
        List<Comment> comments = commentsApi.getAllLikeOrLoveComments(user.getId());
        for (Comment comment : comments) {
            String Key = RC.MOVEMENTS_INTERACT_KEY+comment.getPublishId().toHexString();
            //点赞评论
            if (Objects.equals(comment.getCommentType(), CommentType.LIKE.getType())){
                String userHashKey = RC.MOVEMENT_LIKE_HASH_KEY+comment.getUserId();
                redisTemplate.opsForHash().put(Key,userHashKey,"1");
            }else if (Objects.equals(comment.getCommentType(), CommentType.LOVE.getType())){
                //喜欢评论
                String userHashKey = RC.MOVEMENT_LOVE_HASH_KEY+comment.getUserId();
                redisTemplate.opsForHash().put(Key,userHashKey,"1");
            }
        }
        log.info("用户{}条点赞喜欢信息已加载完成!",comments.size());*/
        //构造返回值
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token",token);
        hashMap.put("isNew",isNew);
        return ResponseEntity.ok(hashMap);
    }

    /**
     * 更新
     * token未修改,前端页面存在信息更新不及时现象
     * @param user 用户
     */
    public void update(User user) {
        userApi.update(user);
    }

    public boolean whetherAlreadyLove(Long userId, Long checkLikeUserId) {
       return userLikeApi.whetherAlreadyLove(userId,checkLikeUserId);
    }
}
